from django.utils import timezone
from rest_framework import serializers
from ..models.purchase import *
from ..models.other import *


# 采购订单
class FaKuyouGoodsPurchaseOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsPurchaseOrder
        fields = '__all__'
        extra_kwargs = {
            'purchase_code': {'required': True},
            'number': {'min_value': 0},
            'all_money': {'min_value': 0}
        }

    def validate_purchase_code(self, value):
        """验证订单号唯一性"""
        if self.instance and self.instance.purchase_code == value:
            return value
        if FaKuyouGoodsPurchaseOrder.objects.filter(purchase_code=value).exists():
            raise serializers.ValidationError("订单号已存在")
        return value


# 采购订单详情
class FaKuyouGoodsPurchaseOrderInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsPurchaseOrderInfo
        fields = '__all__'
        extra_kwargs = {
            'goods_code': {'required': True},
            'number': {'min_value': 0.0001},
            'unit_price': {'min_value': 0}
        }

    def validate(self, data):
        # 数量不能超过可用库存（如果是退货）
        if data.get('purchase_type') == '2' and data.get('number', 0) > data.get('allow_stock', 0):
            raise serializers.ValidationError({"number": "退货数量不能超过可用库存"})
        return data


# 采购单
class FaKuyouGoodsPurchaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsPurchase
        fields = '__all__'
        extra_kwargs = {
            'purchase_code': {'required': True},
            'all_money': {'min_value': 0},
            'number': {'min_value': 0}
        }

    def validate(self, data):
        # 付款金额不能超过应付金额
        if data.get('pay_money', 0) > data.get('real_money', 0):
            raise serializers.ValidationError({"pay_money": "已付款金额不能大于优惠后金额"})

        return data


# 采购详情单
class FaKuyouGoodsPurchaseInfoSerializer(serializers.ModelSerializer):
    # 计算字段
    remaining_amount = serializers.DecimalField(
        max_digits=15,
        decimal_places=4,
        read_only=True,
        help_text='待付款金额'
    )

    class Meta:
        model = FaKuyouGoodsPurchaseInfo
        fields = '__all__'
        extra_kwargs = {
            'goods_code': {'required': True},
            'number': {'min_value': 0.0001},
            'unit_price': {'min_value': 0}
        }

    def validate(self, data):
        # 付款金额不能超过应付金额
        if data.get('pay_money', 0) > data.get('real_money', 0):
            raise serializers.ValidationError({"pay_money": "已付款金额不能大于优惠后金额"})

        return data


# 采购单关联表
class FaKuyouGoodsPurOrdSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsPurOrd
        fields = '__all__'
        extra_kwargs = {
            'order_id': {'required': True},
            'purchase_id': {'required': True}
        }

    def validate(self, data):
        """
        验证关联关系有效性
        1. 避免重复关联
        2. 检查关联ID是否存在（实际项目需添加）
        """
        if FaKuyouGoodsPurOrd.objects.filter(
                order_id=data['order_id'],
                purchase_id=data['purchase_id']
        ).exists():
            raise serializers.ValidationError("该关联关系已存在")
        return data


# 采购详情单关联表
class FaKuyouGoodsPurOrdInfoSerializer(serializers.ModelSerializer):
    # 计算字段
    remaining_amount = serializers.SerializerMethodField()

    class Meta:
        model = FaKuyouGoodsPurOrdInfo
        fields = '__all__'
        extra_kwargs = {
            'order_id': {'required': True},
            'purchase_id': {'required': True},
            'number': {'min_value': 0},
            'all_money': {'min_value': 0}
        }

    def get_remaining_amount(self, obj):
        """计算待付款金额"""
        return float(obj.all_money) - float(obj.money or 0)

    def validate(self, data):
        """业务验证"""
        # 付款金额不能超过总金额
        if data.get('money', 0) > data.get('all_money', 0):
            raise serializers.ValidationError({
                'money': '已付款金额不能大于总金额'
            })

        return data


# 购货退货单
class FaKuyouGoodsExchangeSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsExchange
        fields = '__all__'

    def validate(self, data):
        # 自定义验证逻辑示例
        if data.get('real_money', 0) < 0:
            raise serializers.ValidationError("优惠后金额不能为负数")
        return data


# 购货退货单详情
class FaKuyouGoodsExchangeInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsExchangeInfo
        fields = '__all__'

    def validate(self, data):
        # 自定义验证逻辑示例
        if data.get('number', 0) < 0:
            raise serializers.ValidationError("数量不能为负数")
        if data.get('unit_price', 0) < 0:
            raise serializers.ValidationError("单价不能为负数")
        return data


# 退货关联表
class FaKuyouGoodsExcpurSerializer(serializers.ModelSerializer):
    type_display = serializers.CharField(
        source='get_type_display',
        read_only=True,
        help_text='单据类型显示值'
    )

    class Meta:
        model = FaKuyouGoodsExcpur
        fields = '__all__'


# 退货关联详情单
class FaKuyouGoodsExcpurInfoSerializer(serializers.ModelSerializer):
    type_display = serializers.CharField(
        source='get_type_display',
        read_only=True,
        help_text='类型显示值'
    )
    status_display = serializers.CharField(
        source='get_status_display',
        read_only=True,
        help_text='审核状态显示值'
    )

    class Meta:
        model = FaKuyouGoodsExcpurInfo
        fields = '__all__'

    def validate(self, data):
        # 自定义验证逻辑
        if data.get('money', 0) < 0:
            raise serializers.ValidationError("退款金额不能为负数")
        if data.get('number', 0) < 0:
            raise serializers.ValidationError("数量不能为负数")
        return data
